use std::{fs, path::Path, sync::Mutex};

use bevy::{prelude::*,ecs::system::Commands, log::info};
use nalgebra::Vector2;
use soukoban::Level;

use crate::{board, components::Board, database, resources::{Database, LevelId}};

pub fn setup_database(mut commands: Commands){
    let db_path = crate::settings::app_writeable_dir().join("db.sqlite3");
    let database = database::Database::from_file(Path::new(&db_path));
    database.initialize();

    info!("Loading levels from files");
    let levels_dir = crate::settings::static_resources_dir().join(r"assets/levels/");
    for path in fs::read_dir(&levels_dir).unwrap() {
        let path = path.unwrap().path();
        if !path.is_file() {
            continue;
        }
        info!("     {:?}",path);
        let levels: Vec<_> = Level::load_from_str(&fs::read_to_string(path).unwrap())
            .filter_map(Result::ok)
            .collect();
        database.import_levels(&levels);
    }
    info!("Done");
    commands.insert_resource(Database(Mutex::new(database)));
}


pub fn setup_level(mut commands: Commands,database: Res<Database>){
    let database = database.lock().unwrap();
    let map = database.get_level_by_id(1).unwrap().into();

    commands.spawn(Board{
        board: board::Board::with_map(map),
        tile_size: Vector2::zeros(),
    });

    let next_unsolved_level_id = database
        .next_unsolved_level_id(0)
        .unwrap_or(database.max_level_id().unwrap());
    commands.insert_resource(LevelId(next_unsolved_level_id));
}